package com.zh.risk.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zh.common.entity.JSONResult;
import com.zh.risk.entity.IpTable;
import com.zh.risk.entity.RiskBlackList;
import com.zh.risk.service.BlackListService;
import com.zh.risk.service.IpTableService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * code is far away from bug with the animal protecting
 * ┏┓　　　┏┓
 * ┏┛┻━━━┛┻┓
 * ┃　　　　　　　┃
 * ┃　　　━　　　┃
 * ┃　┳┛　┗┳　┃
 * ┃　　　　　　　┃
 * ┃　　　┻　　　┃
 * ┃　　　　　　　┃
 * ┗━┓　　　┏━┛
 * 　　┃　　　┃神兽保佑
 * 　　┃　　　┃代码无BUG！
 * 　　┃　　　┗━━━┓
 * 　　┃　　　　　　　┣┓
 * 　　┃　　　　　　　┏┛
 * 　　┗┓┓┏━┳┓┏┛
 * 　　　┃┫┫　┃┫┫
 * 　　　┗┻┛　┗┻┛
 *
 * @Description: 黑名单白名单控制器
 * @Author: Liard
 * @Create in: 2020/8/24 11:40
 * @Version: 1.0.1
 */
@Api(value = "黑名单白名单控制器", tags = "IpTableController")
@RestController
@RequestMapping("/firewall")
public class IpTableController {

    @Autowired
    private IpTableService service;

    @Autowired
    private BlackListService blackListService;


    @ApiOperation(value = "分页查询黑/白名单列表", tags = {"getBlackList"}, notes = "分页查询黑/白名单列表")
    @GetMapping("/getBlackList")
    public JSONResult<List<IpTable>> getBlackList(
            @ApiParam(value = "起始页") Integer pageNo,
            @ApiParam(value = "显示数量页面") Integer pageSize,
            @ApiParam(value = "黑/单白名单实体信息", name = "ipTable") IpTable ipTable) {
        JSONResult<List<IpTable>> jsonResult = new JSONResult<>();
        try {
            Page<IpTable> page = new Page<>(pageNo, pageSize);
            IPage<IpTable> result = service.getBlackList(page, ipTable);
            jsonResult.setTotal(result.getTotal());
            jsonResult.setData(result.getRecords());
            jsonResult.setSuccess(true);
            jsonResult.setMessage("查询完成!");
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.setSuccess(false);
            jsonResult.setMessage(e.getLocalizedMessage());
        }
        return jsonResult;
    }

    @ApiOperation(value = "添加黑白名单列表", tags = {"addBlackList"}, notes = "添加黑白名单列表")
    @PutMapping("/addBlackList")
    public JSONResult<Object> addBlackList(@ApiParam(value = "黑名单白名单实体信息", name = "ipTable") IpTable ipTable) {
        JSONResult<Object> jsonResult = new JSONResult<Object>();
        try {
            if (service.addBlackList(ipTable)) {
                jsonResult.setSuccess(true);
                jsonResult.setMessage("添加完成!");
            } else {
                jsonResult.setSuccess(false);
                jsonResult.setMessage("请求错误，请稍后再试.");
            }
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.setSuccess(false);
            jsonResult.setMessage(e.getLocalizedMessage());
        }
        return jsonResult;
    }

    @ApiOperation(value = "修改黑白名单列表", tags = {"modBlackList"}, notes = "修改黑白名单列表")
    @PutMapping("/modBlackList")
    public JSONResult<Object> modBlackList(@ApiParam(value = "黑名单白名单实体信息", name = "ipTable") IpTable ipTable) {
        JSONResult<Object> jsonResult = new JSONResult<Object>();
        try {
            if (service.modBlackList(ipTable) > 0) {
                jsonResult.setSuccess(true);
                jsonResult.setMessage("修改完成!");
            } else {
                jsonResult.setSuccess(false);
                jsonResult.setMessage("请求错误，请稍后再试.");
            }
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.setSuccess(false);
            jsonResult.setMessage(e.getLocalizedMessage());
        }
        return jsonResult;
    }

    @ApiOperation(value = "删除黑白名单列表", tags = {"delBlackInfo"}, notes = "删除黑白名单列表")
    @DeleteMapping("/delBlackInfo")
    public JSONResult<Object> delBlackInfo(@ApiParam(value = "黑名单白名单实体信息", name = "ipTable") IpTable ipTable) {
        JSONResult<Object> jsonResult = new JSONResult<Object>();
        try {
            if (service.delBlackInfo(ipTable) > 0) {
                jsonResult.setSuccess(true);
                jsonResult.setMessage("删除完成!");
            } else {
                jsonResult.setSuccess(false);
                jsonResult.setMessage("请求错误，请稍后再试.");
            }
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.setSuccess(false);
            jsonResult.setMessage(e.getLocalizedMessage());
        }
        return jsonResult;
    }


    @ApiOperation(value = "批量删除黑白名单列表", tags = {"delBatBlackInfo"}, notes = "批量删除黑白名单列表")
    @DeleteMapping("/delBatBlackInfo")
    @ResponseBody
    public JSONResult<Object> delBatBlackInfo(@ApiParam(value = "主键集合", name = "ids") @RequestBody @RequestParam("ids") List<Integer> ids) {
        JSONResult<Object> jsonResult = new JSONResult<Object>();
        try {
            if (service.delBatBlackInfo(ids) > 0) {
                jsonResult.setSuccess(true);
                jsonResult.setMessage("添加完成!");
            } else {
                jsonResult.setSuccess(false);
                jsonResult.setMessage("请求错误，请稍后再试.");
            }
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.setSuccess(false);
            jsonResult.setMessage(e.getLocalizedMessage());
        }
        return jsonResult;
    }


    @ApiOperation(value = "分页查询法人黑/白名单列表", tags = {"getBlackMrcList"}, notes = "分页查询法人黑/白名单列表")
    @GetMapping("/getBlackMrcList")
    public JSONResult<List<RiskBlackList>> getBlackMrcList(
            @ApiParam(value = "起始页") Integer pageNo,
            @ApiParam(value = "显示数量页面") Integer pageSize,
            @ApiParam(value = "黑/单白名单实体信息", name = "blackList") RiskBlackList blackList) {
        JSONResult<List<RiskBlackList>> jsonResult = new JSONResult<>();
        try {
            Page<RiskBlackList> page = new Page<>(pageNo, pageSize);
            blackList.setVal("2");
            IPage<RiskBlackList> result = blackListService.getBlackMrcList(page, blackList);
            jsonResult.setTotal(result.getTotal());
            jsonResult.setData(result.getRecords());
            jsonResult.setSuccess(true);
            jsonResult.setMessage("查询完成!");
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.setSuccess(false);
            jsonResult.setMessage(e.getLocalizedMessage());
        }
        return jsonResult;
    }


    @ApiOperation(value = "添加商户黑名单列表", tags = {"addBlackMrcList"}, notes = "添加商户黑名单列表")
    @PutMapping("/addBlackMrcList")
    public JSONResult<Object> addBlackMrcList(@ApiParam(value = "黑名单白名单实体信息", name = "ipTable") RiskBlackList blackList) {
        JSONResult<Object> jsonResult = new JSONResult<Object>();
        try {
            if (blackListService.addBlackMrcList(blackList)) {
                jsonResult.setSuccess(true);
                jsonResult.setMessage("添加完成!");
            } else {
                jsonResult.setSuccess(false);
                jsonResult.setMessage("请求错误，请稍后再试.");
            }
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.setSuccess(false);
            jsonResult.setMessage(e.getLocalizedMessage());
        }
        return jsonResult;
    }

    @ApiOperation(value = "修改商户黑名单列表", tags = {"modBlackMrcList"}, notes = "修改商户黑名单列表")
    @PutMapping("/modBlackMrcList")
    public JSONResult<Object> modBlackMrcList(@ApiParam(value = "黑名单白名单实体信息", name = "ipTable") RiskBlackList blackList) {
        JSONResult<Object> jsonResult = new JSONResult<Object>();
        try {
            if (blackListService.modBlackMrcList(blackList) > 0) {
                jsonResult.setSuccess(true);
                jsonResult.setMessage("修改完成!");
            } else {
                jsonResult.setSuccess(false);
                jsonResult.setMessage("请求错误，请稍后再试.");
            }
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.setSuccess(false);
            jsonResult.setMessage(e.getLocalizedMessage());
        }
        return jsonResult;
    }

    @ApiOperation(value = "删除商户黑名单列表", tags = {"delBlackMrcInfo"}, notes = "删除商户黑名单列表")
    @DeleteMapping("/delBlackMrcInfo")
    public JSONResult<Object> delBlackMrcInfo(@ApiParam(value = "黑名单白名单实体信息", name = "ipTable") RiskBlackList blackList) {
        JSONResult<Object> jsonResult = new JSONResult<Object>();
        try {
            if (blackListService.delBlackMrcInfo(blackList) > 0) {
                jsonResult.setSuccess(true);
                jsonResult.setMessage("删除完成!");
            } else {
                jsonResult.setSuccess(false);
                jsonResult.setMessage("请求错误，请稍后再试.");
            }
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.setSuccess(false);
            jsonResult.setMessage(e.getLocalizedMessage());
        }
        return jsonResult;
    }


    @ApiOperation(value = "批量删除商户黑名单列表", tags = {"delBatBlackMrcInfo"}, notes = "批量删除商户黑名单列表")
    @DeleteMapping("/delBatBlackMrcInfo")
    @ResponseBody
    public JSONResult<Object> delBatBlackMrcInfo(@ApiParam(value = "主键集合", name = "ids") @RequestBody @RequestParam("ids") List<Integer> ids) {
        JSONResult<Object> jsonResult = new JSONResult<Object>();
        try {
            if (blackListService.delBatBlackMrcInfo(ids) > 0) {
                jsonResult.setSuccess(true);
                jsonResult.setMessage("添加完成!");
            } else {
                jsonResult.setSuccess(false);
                jsonResult.setMessage("请求错误，请稍后再试.");
            }
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.setSuccess(false);
            jsonResult.setMessage(e.getLocalizedMessage());
        }
        return jsonResult;
    }


    @ApiOperation(value = "分页查询区域限制列表", tags = {"getBlackAreaList"}, notes = "分页查询区域限制列表")
    @GetMapping("/getBlackAreaList")
    public JSONResult<List<RiskBlackList>> getBlackAreaList(
            @ApiParam(value = "起始页") Integer pageNo,
            @ApiParam(value = "显示数量页面") Integer pageSize,
            @ApiParam(value = "黑/单白名单实体信息", name = "blackList") RiskBlackList blackList) {
        JSONResult<List<RiskBlackList>> jsonResult = new JSONResult<>();
        try {
            Page<RiskBlackList> page = new Page<>(pageNo, pageSize);
            blackList.setVal("7");
            IPage<RiskBlackList> result = blackListService.getBlackMrcList(page, blackList);
            jsonResult.setTotal(result.getTotal());
            jsonResult.setData(result.getRecords());
            jsonResult.setSuccess(true);
            jsonResult.setMessage("查询完成!");
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.setSuccess(false);
            jsonResult.setMessage(e.getLocalizedMessage());
        }
        return jsonResult;
    }


    @ApiOperation(value = "添加区域黑名单列表", tags = {"addBlackAreaList"}, notes = "添加商户黑名单列表")
    @PutMapping("/addBlackAreaList")
    public JSONResult<Object> addBlackAreaList(@ApiParam(value = "黑名单白名单实体信息", name = "ipTable") RiskBlackList blackList) {
        JSONResult<Object> jsonResult = new JSONResult<Object>();
        try {
            if (blackListService.addBlackMrcList(blackList)) {
                jsonResult.setSuccess(true);
                jsonResult.setMessage("添加完成!");
            } else {
                jsonResult.setSuccess(false);
                jsonResult.setMessage("请求错误，请稍后再试.");
            }
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.setSuccess(false);
            jsonResult.setMessage(e.getLocalizedMessage());
        }
        return jsonResult;
    }

    @ApiOperation(value = "修改商户黑名单列表", tags = {"modBlackAreaList"}, notes = "修改商户黑名单列表")
    @PutMapping("/modBlackAreaList")
    public JSONResult<Object> modBlackAreaList(@ApiParam(value = "黑名单白名单实体信息", name = "ipTable") RiskBlackList blackList) {
        JSONResult<Object> jsonResult = new JSONResult<Object>();
        try {
            if (blackListService.modBlackMrcList(blackList) > 0) {
                jsonResult.setSuccess(true);
                jsonResult.setMessage("修改完成!");
            } else {
                jsonResult.setSuccess(false);
                jsonResult.setMessage("请求错误，请稍后再试.");
            }
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.setSuccess(false);
            jsonResult.setMessage(e.getLocalizedMessage());
        }
        return jsonResult;
    }

    @ApiOperation(value = "删除区域黑名单列表", tags = {"delBlackAreaInfo"}, notes = "删除区域黑名单列表")
    @DeleteMapping("/delBlackAreaInfo")
    public JSONResult<Object> delBlackAreaInfo(@ApiParam(value = "黑名单白名单实体信息", name = "ipTable") RiskBlackList blackList) {
        JSONResult<Object> jsonResult = new JSONResult<Object>();
        try {
            if (blackListService.delBlackMrcInfo(blackList) > 0) {
                jsonResult.setSuccess(true);
                jsonResult.setMessage("删除完成!");
            } else {
                jsonResult.setSuccess(false);
                jsonResult.setMessage("请求错误，请稍后再试.");
            }
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.setSuccess(false);
            jsonResult.setMessage(e.getLocalizedMessage());
        }
        return jsonResult;
    }


    @ApiOperation(value = "批量删除区域黑名单列表", tags = {"delBatBlackAreaInfo"}, notes = "批量删除区域黑名单列表")
    @DeleteMapping("/delBatBlackAreaInfo")
    @ResponseBody
    public JSONResult<Object> delBatBlackAreaInfo(@ApiParam(value = "主键集合", name = "ids") @RequestBody @RequestParam("ids") List<Integer> ids) {
        JSONResult<Object> jsonResult = new JSONResult<Object>();
        try {
            if (blackListService.delBatBlackMrcInfo(ids) > 0) {
                jsonResult.setSuccess(true);
                jsonResult.setMessage("添加完成!");
            } else {
                jsonResult.setSuccess(false);
                jsonResult.setMessage("请求错误，请稍后再试.");
            }
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.setSuccess(false);
            jsonResult.setMessage(e.getLocalizedMessage());
        }
        return jsonResult;
    }

    @ApiOperation(value = "法人黑名单/区域列表上传excel批量新增", tags = {"excelFile"}, notes = "区域列表上传excel批量新增")
    @PostMapping("/excelFile")
    @ResponseBody
    public JSONResult<Object> excelFile(@ApiParam(value = "excel文件", name = "file")  MultipartFile file) {
        JSONResult<Object> jsonResult = new JSONResult<Object>();
        if (blackListService.addBlackMrcListByExcel(file)) {
            jsonResult.setSuccess(true);
            jsonResult.setMessage("添加完成!");
        } else {
            jsonResult.setSuccess(false);
            jsonResult.setMessage("请求错误，请稍后再试.");
        }
        return jsonResult;
    }

    @ApiOperation(value = "Ip地址的excel批量新增", tags = {"excelFile"}, notes = "Ip地址的excel批量新增")
    @PostMapping("/ipExcelFile")
    @ResponseBody
    public JSONResult<Object> ipExcelFile(@ApiParam(value = "excel文件", name = "file")  MultipartFile file) {
        JSONResult<Object> jsonResult = new JSONResult<Object>();
        if (service.addIpTableByExcel(file)) {
            jsonResult.setSuccess(true);
            jsonResult.setMessage("添加完成!");
        } else {
            jsonResult.setSuccess(false);
            jsonResult.setMessage("请求错误，请稍后再试.");
        }
        return jsonResult;
    }

    @ApiOperation(value = "IP地址Excel模板下载" , tags = "getTongLianLogDownload" , notes = "IP地址Excel模板下载")
    @GetMapping("/getIpTemplateDownload")
    public void getTongLianLogDownload(HttpServletResponse response) throws IOException {
        String[] header  = new String[]{"ip地址","状态（0.封禁，1.正常）","类型（1.白名单,2黑名单）"};
        //创建excel
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("IP地址模板");
        //设置表格列宽度为20个字节
        sheet.setDefaultColumnWidth(20);
        HSSFRow headrow = sheet.createRow(0);
        for (int i = 0; i < header.length; i++) {
            HSSFCell cell = headrow.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(header[i]);
            cell.setCellValue(text);
        }
        List<IpTable> resultData = new ArrayList();
        for(int i=0 ; i<2;i++){
            IpTable ipTable = new IpTable();
            ipTable.setIp("127.0.0."+i);
            ipTable.setStatus(i);
            ipTable.setType(i+1);
            resultData.add(ipTable);
        }

        for(int i=0;i<resultData.size();i++){
            IpTable ipTable = resultData.get(i);
            HSSFRow row1 = sheet.createRow(i+1);
            row1.createCell(0).setCellValue(ipTable.getIp());
            row1.createCell(1).setCellValue(ipTable.getStatus());
            row1.createCell(2).setCellValue(ipTable.getType());
        }
        String fileName = "IP地址模板";
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=" + new String( fileName.getBytes("gb2312"), "ISO8859-1" ) + ".xls");
        response.flushBuffer();
        workbook.write(response.getOutputStream());
    }

    @ApiOperation(value = "法人黑名单/区域列表Excel模板下载" , tags = "getBlackMrcemplateDownload" , notes = "法人黑名单/区域列表Excel模板下载")
    @GetMapping("/getBlackMrcemplateDownload")
    public void getBlackMrcemplateDownload(HttpServletResponse response) throws IOException {
        String[] header  = new String[]{"地区编码/身份证号码","地区名称/法人名称","类型：2为法人黑名单，7为区域列表，整数"};
        //创建excel
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("法人黑名单和区域列表Excel模板");
        //设置表格列宽度为20个字节
        sheet.setDefaultColumnWidth(40);
        HSSFRow headrow = sheet.createRow(0);
        for (int i = 0; i < header.length; i++) {
            HSSFCell cell = headrow.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(header[i]);
            cell.setCellValue(text);
        }
        List<RiskBlackList> resultData = new ArrayList();
        for(int i=0 ; i<2;i++){
            RiskBlackList riskBlackList = new RiskBlackList();
            riskBlackList.setRiskObj("12321321"+i);
            riskBlackList.setDescription(i==0? "云城区":"李先生");
            riskBlackList.setType(i==0? 2: 7);
            resultData.add(riskBlackList);
        }

        for(int i=0;i<resultData.size();i++){
            RiskBlackList riskBlackList = resultData.get(i);
            HSSFRow row1 = sheet.createRow(i+1);
            row1.createCell(0).setCellValue(riskBlackList.getRiskObj());
            row1.createCell(1).setCellValue(riskBlackList.getDescription());
            row1.createCell(2).setCellValue(riskBlackList.getType());
        }
        String fileName = "法人黑名单/区域列表模板";
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=" + new String( fileName.getBytes("gb2312"), "ISO8859-1" ) + ".xls");
        response.flushBuffer();
        workbook.write(response.getOutputStream());
    }

}